package com.ctsi.auth.vcc.manager.impl;

import com.ctsi.auth.vcc.manager.UserAccoutLockCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangjw
 * @className RedisUserAccountLockCache
 * @description 基于redis实现用户锁定策略
 * @date 2019/2/27 13:59
 **/
@Component
public class RedisUserAccountLockCache implements UserAccoutLockCache {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    public void remove(String cacheName, String userName) {
        redisTemplate.delete(cacheName + ":" + userName);
    }

    /**
     * 获取剩余次数
     *
     * @param cacheName
     * @param userName
     * @return
     */
    @Override
    public int get(String cacheName, String userName) {

        return (int) redisTemplate.opsForValue().get(cacheName + ":" + userName);
    }

    /**
     * 初始化缓存
     *
     * @param cacheName
     * @param userName
     * @param initValue 初始值
     */
    @Override
    public void initCache(String cacheName, String userName, int initValue) {
        String key = cacheName + ":" + userName;
        boolean isExit = redisTemplate.hasKey(key);
        if (!isExit) {
            redisTemplate.opsForValue().set(key,initValue);
            redisTemplate.expire(key,24, TimeUnit.HOURS);
        }
    }

    @Override
    public int getAndIncrement(String cacheName, String userName,Integer lockTime) {
        String key = cacheName + ":" + userName;
        int i = (int) redisTemplate.opsForValue().get(key);
        if (i == 1) {
            redisTemplate.opsForValue().set(key,0);
            redisTemplate.expire(key,lockTime == null? 300 : lockTime, TimeUnit.SECONDS); // 默认锁定5分种
            return i;
        } else if (i == 0) {
            return 0;
        }
        redisTemplate.boundValueOps(key).increment(-1);
        redisTemplate.expire(key,24, TimeUnit.HOURS);
        return i;
    }
}
